package com.coder520.mamabike.security;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by ASUS on 2017/8/11.
 */
public class AESUtil {


    public static String encrypt(String data,String key){
        try {
            SecretKeySpec spec = new SecretKeySpec(key.getBytes("utf-8"),"AES");
            Cipher cipher  = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE,spec,new IvParameterSpec(new byte[cipher.getBlockSize()]));
            byte[] bys = cipher.doFinal(data.getBytes("utf-8"));
            return Base64Utils.encode(bys);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String data,String key){
        try {
            SecretKeySpec spec = new SecretKeySpec(key.getBytes("utf-8"),"AES");
            Cipher cipher  = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE,spec,new IvParameterSpec(new byte[cipher.getBlockSize()]));
            byte[] origin = Base64Utils.decode(data);
            byte[] result = cipher.doFinal(origin);
            return new String(result,"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
